package com.dnbns.lib;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

/**
 * This helper class download images from the Internet and binds those with the provided ImageView.
 *
 * <p>It requires the INTERNET permission, which should be added to your application's manifest
 * file.</p>
 *
 * A local cache of downloaded images is maintained internally to improve performance.
 */
public class ImageDownloader {
    private static final String LOG_TAG = "ImageDownloader";

    public enum Mode { NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT }
    private Mode mode = Mode.CORRECT;
    private int BUFFER_SIZE = 640;
    private ProgressBar pb = null;
    /**
     * 이 클래스는 특정한 URL 경로에 위치한 이미지를 다운로드한 후 해당 이미지를 뷰에 바인드함.
     * @param url 이미지를 다운받을 URL 경로.
     * @param imageView 다운받은 이미지를 셋팅할 뷰.
     */
    public void download(String url, ImageView imageView) {
//        resetPurgeTimer();
        Bitmap bitmap = getBitmapFromCache(url);
        BUFFER_SIZE = 640;
        pb = null;
        
        if (bitmap == null) {
            forceDownload(url, imageView);
        } else {
            cancelPotentialDownload(url, imageView);
            imageView.setImageBitmap(bitmap);
        }
    }

	public void download(String url, ImageView imageView, int size) {
//		resetPurgeTimer();
		Bitmap bitmap = getBitmapFromCache(url);
		BUFFER_SIZE = size;
	    pb = null;

		if (bitmap == null) {
			forceDownload(url, imageView);
		} else {
			cancelPotentialDownload(url, imageView);
			imageView.setImageBitmap(bitmap);
		}
	}

	public void download(String url, ImageView imageView, ProgressBar pb) {
//		resetPurgeTimer();
		Bitmap bitmap = getBitmapFromCache(url);
		this.pb = pb;

		pb.setVisibility(View.VISIBLE);
		if (bitmap == null) {
			forceDownload(url, imageView);
		} else {
			cancelPotentialDownload(url, imageView);
			imageView.setImageBitmap(bitmap);
    		pb.setVisibility(View.GONE);
		}
	}
    /**
     * Same as download but the image is always downloaded and the cache is not used.
     * Kept private at the moment as its interest is not clear.
     */
    private void forceDownload(String url, ImageView imageView) {
        // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys.
        if (url == null) {
        	
//            imageView.setImageBitmap(BitmapFactory.decodeResource(imageView.getResources(), R.drawable.noimage));
            return;
        }

        if (cancelPotentialDownload(url, imageView)) {
            switch (mode) {
                case NO_ASYNC_TASK:
                    Bitmap bitmap = downloadBitmap(url);
                    addBitmapToCache(url, bitmap);
                    imageView.setImageBitmap(bitmap);
                    break;

                case NO_DOWNLOADED_DRAWABLE:
                    imageView.setMinimumHeight(156);
                    BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
                    task.execute(url);
                    break;

                case CORRECT:
                    task = new BitmapDownloaderTask(imageView);
                    DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
                    imageView.setImageDrawable(downloadedDrawable);
                    imageView.setMinimumHeight(156);
                    task.execute(url);
                    break;
            }
        }
    }

    /**
     * 
     * 새로운 다운로드 작업이 시작됨으로, 현재 ImageView와 연관된 이미지 다운로드 작업을 정지 시키는 역할을 수행합니다.
     * 진행중인 다운로드 작업을 정지하기 위해 AsyncTask의 cancel 메서드를 사용합니다.
     * 일반적으로 'true' 값을 리턴하며, 새로운 다운로드 작업이 시작됩니다. 다만, 이미 동일한 URL에 대하여 다운로드가 진행 중인 경우에는
     * 기존 다운로드 작업을 취소하지 않고 계속 진행되도록 구현되었습니다.
     * @param url 이미지 다운로드 URL
     * @param imageView 다운된 이미지 표시.
     * @return
     */
    private static boolean cancelPotentialDownload(String url, ImageView imageView) {
        BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

        if (bitmapDownloaderTask != null) {
            String bitmapUrl = bitmapDownloaderTask.url;
            if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
                bitmapDownloaderTask.cancel(true);
            } else {
                // The same URL is already being downloaded.
                return false;
            }
        }
        return true;
    }

    /**
     * 
     * @param imageView 모든 imageView
     * @return 현재 진행되고 있는 다운로드 작업을 검색합니다.
     * 작업이 없는 경우 null.
     */
    private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
        if (imageView != null) {
            Drawable drawable = imageView.getDrawable();
            if (drawable instanceof DownloadedDrawable) {
                DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
                return downloadedDrawable.getBitmapDownloaderTask();
            }
        }
        return null;
    }

    /**
     * 안드로이드 프레임워크에서 제공하는 HTTP 관련 클래스를 사용하여, 웹에서 이미지를 다운로드 하는 메소드.
     */
    Bitmap downloadBitmap(String url) {
        final int IO_BUFFER_SIZE = 1 * BUFFER_SIZE;
    	
        // AndroidHttpClient is not allowed to be used from the main thread
        final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() :
            AndroidHttpClient.newInstance("Android");
        final HttpGet getRequest = new HttpGet(url);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            //페이스북api같이 프로필 사진등을 리다이렉션 해주는 주소로 줄때 발행하는 예외처리.
            //status 값이 301/302
            if (statusCode == 301 || statusCode == 302){
            	Header redirect = response.getFirstHeader("Location");
            	if(client instanceof AndroidHttpClient)
            		((AndroidHttpClient)client).close();
            	return downloadBitmap(redirect.getValue());
            }
            if (statusCode != HttpStatus.SC_OK) {
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();
                    
                    // return BitmapFactory.decodeStream(inputStream);
                    // Bug on slow connections, fixed in future release.
//                  BitmapFactory.Options op = new BitmapFactory.Options();
//                  op.inSampleSize = 2;
//                  return BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, op);
                    
                    BitmapFactory.Options op = new BitmapFactory.Options();
                    op.inJustDecodeBounds = true;
                    
                    BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, op);

                    if(op.outHeight * op.outWidth >= IO_BUFFER_SIZE * IO_BUFFER_SIZE){
                    	op.inSampleSize = (int)Math.pow(2, 
                    			(int)Math.round(Math.log(IO_BUFFER_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
//                    	Log.d("TEST", "#### "+op.inSampleSize);
                    }

                    op.inJustDecodeBounds = false;
                    
                    response = client.execute(getRequest);
                    final int nRetryStatusCode = response.getStatusLine().getStatusCode();
                    
                    if (nRetryStatusCode != HttpStatus.SC_OK) 
                    {
                        return null;
                    }
                    
                    final HttpEntity reEntity = response.getEntity();
                    
                    if (reEntity != null)
                    {
                    	InputStream reInputStream = null;
                    	
                    	try
                    	{
                    		reInputStream = reEntity.getContent();
                    		final Bitmap imgBitmap = BitmapFactory.decodeStream(new FlushedInputStream(reInputStream), null, op);
                            
                            return imgBitmap;
                    	}
                    	finally 
                        {
                    		 if (reInputStream != null) 
                             {
                    			 reInputStream.close();
                             }
                    		 
                    		 reEntity.consumeContent();
                        }
                    }
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (IOException e) {
            getRequest.abort();
            Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
        } catch (IllegalStateException e) {
            getRequest.abort();
            Log.w(LOG_TAG, "Incorrect URL: " + url);
        } catch (Exception e) {
            getRequest.abort();
            Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
        } finally {
            if ((client instanceof AndroidHttpClient)) {
                ((AndroidHttpClient) client).close();
            }
        }
        return null;
    }

    /**
     * 네크워크 커넥션이 느린경우 BitmapFactory.decodeStrem이 정상적으로 작동하지 않는 버그가 있음.
     * 이 클래스는 스트림이 끝나지 않는 한, skip() 메서드가 실재로 전달받은 바이트 수 만큼을 건너띄도록 구현되었다.
     */
    static class FlushedInputStream extends FilterInputStream {
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < n) {
                long bytesSkipped = in.skip(n - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break;  // we reached EOF
                    } else {
                        bytesSkipped = 1; // we read one byte
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }

    /**
     * 
     * @author JJTrading
     * 이미지를 다운로드 작업을 실재로 수행하는 AsyncTask 클래스입니다.
     * execute 메서드를 통해 다운로드가 시작되며, execute 메서드를 즉시 리턴합니다.
     * execute 메서드는 UI 스레드에서 호출되도록 구현되었습니다.
     * 
     */
    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
        private String url;
        private final WeakReference<ImageView> imageViewReference;

        public BitmapDownloaderTask(ImageView imageView) {
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        /**
         * doInBackGround는 메인 스레드와 별개의 스레드에서 수행됩니다.(downloadBitmap 메서드를 호출함)
         */
        @Override
        protected Bitmap doInBackground(String... params) {
            url = params[0];
            return downloadBitmap(url);
        }

        /**
         * 태스크가 종료된 시점에 UI 스레드에서 실행됩니다.
         * 이 메서드는 인자로 넘겨받은 Bitmap 을 미리 지정된 ImageView에 설정합니다.
         * ImageView가 WeakReference로 저장되어 있기때문에 Activity가 종료된 후에도 GC가 해당 ImageView를 제거 못하는 것을 방지함.
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }
            
            //404 Error일때 No Image를 띄어준다.
            if(bitmap == null){
            	ImageView imageView = imageViewReference.get();
            	if(imageView != null)
//            		imageView.setImageBitmap(BitmapFactory.decodeResource(imageView.getResources(), R.drawable.noimage));

            	if ( pb != null ){
            		pb.setVisibility(View.GONE);
            	}
            	return;
            }

            addBitmapToCache(url, bitmap);

            if (imageViewReference != null) {
            	if ( pb != null ){
            		pb.setVisibility(View.GONE);
            	}
                ImageView imageView = imageViewReference.get();
                BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
                // Change bitmap only if this process is still associated with it
                // Or if we don't use any bitmap to task association (NO_DOWNLOADED_DRAWABLE mode)
                if ((this == bitmapDownloaderTask) || (mode != Mode.CORRECT)) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    }

    /**
     * 
     * @author JJTrading
     * 각각의 ImageView가 마지막에 다운로드 된 이미지만을 기억하도록 구현함.
     * 다운로드가 진행중인 동안 임시로 ImageView에 바인드 되는 커스텀한 Drawable 클래스를 이용하여 ImageView에 부가 정보를 추가합니다.
     * DownloadedDrawable은 다운로드 중인 이미지가 있는 경우, ImageView 에 검은 화면을 표시하기 위하며 ColorDrawable을 상속받아 구현되었습니다.
     *
     */
    @SuppressWarnings("deprecation")
    static class DownloadedDrawable extends BitmapDrawable {
        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

		public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
        	//다운로드 진행중일때 대처 이미지.
//            super(BitmapFactory.decodeResource(bitmapDownloaderTask.imageViewReference.get().getResources(), R.drawable.photo_list_loding));
            bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
        }

        public BitmapDownloaderTask getBitmapDownloaderTask() {
            return bitmapDownloaderTaskReference.get();
        }
    }

    public void setMode(Mode mode) {
        this.mode = mode;
        clearCache();
    }

    
    /*
     * Cache-related fields and methods.
     * 
     * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the
     * Garbage Collector.
     */
    
    private static final int HARD_CACHE_CAPACITY = 1000;
    private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds

    // Hard cache, with a fixed maximum capacity and a life duration
    private final HashMap<String, Bitmap> sHardBitmapCache =
        new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY / 2, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
            if (size() > HARD_CACHE_CAPACITY) {
                // Entries push-out of hard reference cache are transferred to soft reference cache
                sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));
                return true;
            } else
                return false;
        }
    };

    // Soft cache for bitmaps kicked out of hard cache
    private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache =
        new ConcurrentHashMap<String, SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);

    private final Handler purgeHandler = new Handler();

    private final Runnable purger = new Runnable() {
        public void run() {
            clearCache();
        }
    };

    /**
     * Adds this bitmap to the cache.
     * @param bitmap The newly downloaded bitmap.
     */
    private void addBitmapToCache(String url, Bitmap bitmap) {
        if (bitmap != null) {
            synchronized (sHardBitmapCache) {
                sHardBitmapCache.put(url, bitmap);
            }
        }
    }

    /**
     * @param url The URL of the image that will be retrieved from the cache.
     * @return The cached bitmap or null if it was not found.
     */
    public Bitmap getBitmapFromCache(String url) {
        // First try the hard reference cache
        synchronized (sHardBitmapCache) {
            final Bitmap bitmap = sHardBitmapCache.get(url);
            if (bitmap != null) {
                // Bitmap found in hard cache
                // Move element to first position, so that it is removed last
                sHardBitmapCache.remove(url);
                sHardBitmapCache.put(url, bitmap);
                return bitmap;
            }
        }

        // Then try the soft reference cache

    	SoftReference<Bitmap> bitmapReference = null;
        if(url != null){
        	bitmapReference = sSoftBitmapCache.get(url);
        }
        
        if (bitmapReference != null) {
            final Bitmap bitmap = bitmapReference.get();
            if (bitmap != null) {
                // Bitmap found in soft cache
                return bitmap;
            } else {
                // Soft reference has been Garbage Collected
                sSoftBitmapCache.remove(url);
            }
        }

        return null;
    }
 
    /**
     * Clears the image cache used internally to improve performance. Note that for memory
     * efficiency reasons, the cache will automatically be cleared after a certain inactivity delay.
     */
    public void clearCache() {
        sHardBitmapCache.clear();
        sSoftBitmapCache.clear();
    	Log.d("TEST", "clearCache!!!!!!!");
    }

    /**
     * Allow a new delay before the automatic cache clear is done.
     */
    public void resetPurgeTimer() {
        purgeHandler.removeCallbacks(purger);
        purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE*3);
    }
}